//
//  HttpEngine.m
//  UCodeCRM
//
//  Created by 邓永军 on 2020/1/7.
//  Copyright © 2020 Huajin. All rights reserved.
//

#import "HttpEngine.h"
#import "SynthesizeSingleton.h"
#import "UCUserModel.h"
#define KUrl(path)        [NSString stringWithFormat:@"%@%@",KHost,path]


@implementation HttpEngine

SYNTHESIZE_SINGLETON_FOR_CLASS(HttpEngine)

-(NSURLSessionDataTask *)logingWithUsername:(NSString *)username passWorld:(NSString *)passWorld success:(AFResponseBlock)success failure:(AFResponseErrorBlock)failure{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:username forKey:@"username"];
    [dic setValue:passWorld forKey:@"password"];
    return [self POSTstartOperationWithPath:@"api-crm/pswLogin"  params:dic success:success failure:failure];
}

//公海
-(NSURLSessionDataTask *)customerPoolListWithKeywords:(NSString *)keywords level:(NSString *)level pageNum:(int  )pageNum pageSize:(NSString *)pageSize source:(NSString *)source success:(AFResponseBlock)success failure:(AFResponseErrorBlock)failure{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:keywords forKey:@"keywords"];
    [dic setValue:level forKey:@"level"];
    [dic setValue:@(1) forKey:@"pageNum"];
      [dic setValue:@(20) forKey:@"pageSize"];
    [dic setValue:keywords forKey:@"keywords"];
      [dic setValue:source forKey:@"source"];
    return [self GETStartOperationWithPath:@"api-crm/crm-customer/poolList"  params:dic success:success failure:failure];
}

//非公海
-(NSURLSessionDataTask *)customerListWithKeywords:(NSString *)keywords level:(NSString *)level pageNum:(int  )pageNum pageSize:(NSString *)pageSize source:(NSString *)source prole:(NSString *)prole userIds:(NSArray *)userIds  success:(AFResponseBlock)success failure:(AFResponseErrorBlock)failure{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:keywords forKey:@"keywords"];
    [dic setValue:level forKey:@"level"];
    [dic setValue:@(1) forKey:@"pageNum"];
      [dic setValue:@(20) forKey:@"pageSize"];
    [dic setValue:keywords forKey:@"keywords"];
      [dic setValue:source forKey:@"source"];
    [dic setValue:prole forKey:@"prole"];
    NSString *uidString = [userIds jsonStringEncoded];
    [dic setValue:uidString forKey:@"userIds"];
    return [self GETStartOperationWithPath:@"api-crm/crm-customer/list"  params:dic success:success failure:failure];
}



//{ "address": "", "areaId": 0, "cityId": 0, "contactsId": 0, "contactsName": "", "contactsSex": 0, "industry": 0, "level": 2, "mobile": "", "name": "", "nextTime": "", "provinceId": 0, "remark": "", "source": 0, "telephone": "", "website": "" }
//创建
-(NSURLSessionDataTask *)customerCreateWithAddress:(NSString *)address areaId:(NSString *)areaId cityId:(NSString *)cityId contactsId:(NSString *)contactsId contactsName:(NSString *)contactsName  contactsSex:(NSString *)contactsSex industry:(NSString *)industry level:(NSString *)level mobile:(NSString *)mobile name:(NSString *)name nextTime:(NSString *)nextTime provinceId:(NSString *)provinceId remark:(NSString *)remark source:(NSString *)source telephone:(NSString *)telephone website:(NSString *)website   success:(AFResponseBlock)success failure:(AFResponseErrorBlock)failure{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:address forKey:@"address"];
    [dic setValue:areaId forKey:@"areaId"];
    [dic setValue:cityId forKey:@"cityId"];
      [dic setValue:contactsId forKey:@"contactsId"];
    [dic setValue:contactsName forKey:@"contactsName"];
      [dic setValue:contactsSex forKey:@"contactsSex"];
    
      [dic setValue:industry forKey:@"industry"];
      [dic setValue:level forKey:@"level"];
      [dic setValue:mobile forKey:@"mobile"];
      [dic setValue:name forKey:@"name"];
      [dic setValue:nextTime forKey:@"nextTime"];
      [dic setValue:provinceId forKey:@"provinceId"];
    [dic setValue:remark forKey:@"remark"];
      [dic setValue:source forKey:@"source"];
      [dic setValue:telephone forKey:@"telephone"];
      [dic setValue:website forKey:@"website"];
    return [self POSTstartOperationWithPath:@"api-crm/crm-customer/create"  params:dic success:success failure:failure];
}


- (NSURLSessionDataTask *)POSTstartOperationWithPath:(NSString *)string params:(NSMutableDictionary *)param success:(AFResponseBlock)success failure:(AFResponseErrorBlock)failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFHTTPRequestSerializer *serializer =  [AFHTTPRequestSerializer serializer];
    [serializer setValue:[UCUserModel sharedUCUserModel].token forHTTPHeaderField:@"token"];
    manager.requestSerializer = serializer;
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
     
    
//    NSString *bodystr = AFQueryStringFromParameters(param);
//          NSString *url =     url = [[KUrl(string) stringByAppendingString:@"?"] stringByAppendingString:bodystr];
    
    return  [manager POST:KUrl(string) parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@%@",task.originalRequest.URL,[param description]);
        NSLog(@"%@ ",[responseObject jsonPrettyStringEncoded]);
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        NSLog(@"%@%@",task.originalRequest.URL,[param description]);
        NSLog(@"%@",error.localizedDescription);
    }];
    
}


- (NSURLSessionDataTask *)GETStartOperationWithPath:(NSString *)string params:(NSMutableDictionary *)param success:(AFResponseBlock)success failure:(AFResponseErrorBlock)failure
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];;
    manager.requestSerializer.timeoutInterval = 60;
//    [param setValue:@"7" forKey:@"device"];
//    [param setValue:[HJUserInfo sharedHJUserInfo].token forKey:@"token"];
//    [param setValue:[[UIDevice currentDevice] systemVersion] forKey:@"systemVersion"];
//    [param setValue:BundleShortVersionString forKey:@"appVersion"];
//    [param setValue:[HJUserInfo sharedHJUserInfo].userid forKey:@"userid"];
//    if (![HJUserInfo sharedHJUserInfo].userid) {
//        [param setValue:[DataManager bannerBackId] forKey:@"userid"];
//    }
//    NSString *udidString = [HJUUID getUUID];
//    [param setValue:udidString forKey:@"uuid"];
    //     manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    AFHTTPRequestSerializer *serializer =  [AFHTTPRequestSerializer serializer];
    [serializer setValue:[UCUserModel sharedUCUserModel].token forHTTPHeaderField:@"Authorization"];
    //    serializer.cachePolicy = NSURLRequestReturnCacheDataDontLoad ;
    ////    NSURLRequestReturnCacheDataElseLoad
    //    [serializer willChangeValueForKey:@"timeoutInterval"];
    //
    //    serializer.timeoutInterval = 10.f;
    //
    //    [serializer didChangeValueForKey:@"timeoutInterval"];
    //    NSURLRequestReloadRevalidatingCacheData
    manager.requestSerializer = serializer;
    
    return  [manager GET:KUrl(string) parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@%@",task.originalRequest.URL,[param description]);
        NSLog(@"%@ ",[responseObject jsonPrettyStringEncoded]);
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        NSLog(@"%@",error.localizedDescription);
    }];
}

- (NSURLSessionDataTask *)startOperationWithURl:(NSString *)url params:(NSMutableDictionary *)param success:(AFResponseBlock)success failure:(AFResponseErrorBlock)failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFHTTPRequestSerializer *serializer =  [AFHTTPRequestSerializer serializer];
    manager.requestSerializer = serializer;
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
  
    
    
    return  [manager POST:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@%@",task.originalRequest.URL,[param description]);
        NSLog(@"%@ ",[responseObject jsonPrettyStringEncoded]);
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        NSLog(@"%@%@",task.originalRequest.URL,[param description]);
        NSLog(@"%@",error.localizedDescription);
    }];
    
}



@end


@implementation NSDictionary (UCAdd)

- (BOOL)isSuccess{
    
    id stateCode = self[@"code"];
    if ([stateCode isKindOfClass:[NSNumber class]]) {
        return [stateCode integerValue] == 0;
    }else{
        return [stateCode integerValue] == 200;
    }
}

- (id )responseDic{
    return self[@"data"];
}

- (NSString *)errorMessage{
    return self[@"message"];
}

@end
